"use strict"

const Service = require('egg').Service
const moment = require('moment')

class CategoryService extends Service {
    /**
     * @param {列表查询} param 
     * pid(分类父级id -否), page(页码 -否), rows(页数-否)
     */
    async list(param) {
        const { app, ctx } = this
        let option = {
            where: { pid: param.pid? param.pid : 0},
            attributes: ['id', 'name', 'rank', 'img', 'exhibition_img', 'pid', 'create_time'],
            include: [
                {
                    model: app.model.Category,
                    as: 'children',
                    attributes: ['id', 'name', 'rank', 'img', 'exhibition_img', 'pid', 'create_time'],
                }
            ],
            distinct: true,
        }
        if(param.page && param.rows) {
            option.limit = 1 * param.rows,
            option.offset = (param.page - 1) * param.rows
        }
        try {
            const result = await app.model.Category.findAndCountAll(option)
            return ctx.app.returnHint(result, '查询成功').definedSucceed
        }catch(err) {
            console.log(err);
            return ctx.app.returnHint(err, '查询失败').definedError
        }
    }

     /**
     * @param {详情} param
     * id(分类id) 
     */
    async details(param) {
        const { app, ctx } = this
        const id = param.id
        try{
            const result = await app.model.Category.findOne({
                where: { id },
                attributes: ['id', 'name', 'rank', 'img', 'exhibition_img', 'pid'],
                include: [
                    { model: app.model.Category, as: 'parent', attributes: ['name'],}
                ]
            })
            return ctx.app.returnHint(result, '查询成功').definedSucceed
        } catch(err) {
            console.log(err)
            return ctx.app.returnHint(err, '查询失败').definedError
        }
    }

    /**
     * 
     * @param {添加} param 
     * name(分类名称), rank(分类级别),img(分类图片),exhibition_img(分类展示图),pid(分类父级id)
     */
    async add(param) {
        const { app, ctx } = this
        // 开始事务
        const transaction = await app.model.transaction();
        try {
            const data = {
                name: param.name,
                rank: param.rank,
                img: param.img,
                exhibition_img: param.exhibition_img,
                pid: param.pid,
                create_time: moment().format('YYYY-MM-DD HH:mm:ss')
            }
            // 添加数据
            const result = await app.model.Category.findOrCreate({
                defaults: data,
                fields: ['name', 'rank', 'img', 'exhibition_img', 'pid', 'create_time'],
                where: { name: param.name, pid: param.pid },
                transaction
            })
            // 提交事务
            await transaction.commit();
            if(result[1]){
                return ctx.app.returnHint(result[0], '添加成功').definedSucceed
            }else{
                return ctx.app.returnHint(null, '分类已存在').definedSucceed
            }
        }catch(err) {
            console.log(err);
            await transaction.rollback();// 捕获异常后回滚事务！！
            return ctx.app.returnHint(err, '添加失败').definedError
        }
    }

    /**
     * 
     * @param {编辑} param 
     * id
     */
    async redact(param) {
        const { app, ctx } = this
        // 开始事务
        const transaction = await app.model.transaction();
        try {
            const data = {
                name: param.name,
                rank: param.rank,
                img: param.img,
                exhibition_img: param.exhibition_img,
                pid: param.pid,
                update_time: moment().format('YYYY-MM-DD HH:mm:ss')
            }
            // 更新数据
            const result = await app.model.Category.update(data, {
                where: { id: param.id },
                transaction
            })            
            // 提交事务
            await transaction.commit();
            return ctx.app.returnHint(result, '更新成功').definedSucceed
        }catch(err) {
            console.log(err);
            await transaction.rollback();// 捕获异常后回滚事务！！
            return ctx.app.returnHint(err, '更新失败').definedError
        }
    }

    /**
     * 
     * @param {删除} param 
     * id(分类id)
     */
    async del(param) {
        const { app, ctx } = this
        const transaction = await app.model.transaction(); // 开始事务
        const id = param.id

        try{
            let result = await app.model.Category.destroy({
                where: { id },
                transaction
            })
            // 查询子分类
            let childs = await app.model.Category.findAll({
                where: { pid: id },
                transaction
            })
            if(childs.length){
                await app.model.Category.destroy({
                    where: { pid: id },
                    limit: childs.length,
                    transaction
                })
            }
            // 事务提交
            await transaction.commit();
            return ctx.app.returnHint(result, '删除成功').definedSucceed
        } catch(err) {
            console.log(err)
            await transaction.rollback();// 捕获异常后回滚事务！！
            return ctx.app.returnHint(err, '删除失败').definedError
        }
    }

}

module.exports = CategoryService